﻿@using viBook.Common
@using viBook.Helpers
@using viBook.Models
@model Book
@{
    var totalCommentPage = (int) Math.Ceiling((double) Model.NumberOfComments/Constant.MaximunCommentPerChapter);
    totalCommentPage = totalCommentPage == 0 ? 1 : totalCommentPage;
    bool isShowNextButton = totalCommentPage > 1;
    var userBookCollection = ViewBag.UserBookCollection as IEnumerable<Book>;
    var authorBookCollection = ViewBag.AuthorBookCollection as IEnumerable<Book>;
}
<script type="text/javascript">
         function Book(description, id, title, coverImage, numberOfPages, numberOfChapters, numberOfLikes, numberOfViews, numberOfComments, uploaderImage, uploader, uploadedBy, uploadedDateString, classBinding) {
             return {
                 description: description,
                 id: id,
                 title: title,
                 coverImage: coverImage,
                 numberOfPages: numberOfPages,
                 numberOfChapters: numberOfChapters,
                 numberOfLikes: numberOfLikes,
                 numberOfViews: numberOfViews,
                 numberOfComments: numberOfComments,
                 uploaderImage: uploaderImage,
                 uploader: uploader,
                 uploadedBy: uploadedBy,
                 uploadedDateString: uploadedDateString,
                 classBinding: classBinding,
                 detail: function() {
                     window.location = '/books/details/' + this.id;

                 }
             };
         }

         function Comment() {
             return new Comment(0,"","","","",0,false,false,false);
         }

         function ContentTag(id, contentTagName, numberOfBook) {
             return {
                 id: ko.observable(id),
                 contentTagName: ko.observable(contentTagName),
                 numberOfBook: ko.observable(numberOfBook)
             };
         }

         function Comment(id, username, userImage, content, createdDate, numberOfLike, isLiked,isReported, isAuthorized) {
             return {
                 id: ko.observable(id),
                 username: ko.observable(username),
                 userImage: ko.observable(userImage),
                 content: ko.observable(content),
                 createdDate: ko.observable(createdDate),
                 numberOfLike: ko.observable(numberOfLike),
                 isLiked: ko.observable(isLiked),
                 bookId: ko.observable( @Model.Id ),
                 isAuthorized: ko.observable(isAuthorized),
                 isReported: ko.observable(isReported),
                 likeFunc: function() {
                     var currentTag = this;
                     $.ajax({
                             url: '@Url.Action("Like", "BookComments")',
                             type: 'POST',
                             data: ko.toJSON({ id: this.id }),
                             contentType: 'APPLICATION/JSON',
                             success: function(result) {
                                 if (result.success) {
                                     if (currentTag.isLiked()) {
                                         currentTag.numberOfLike(currentTag.numberOfLike() - 1);
                                     } else {
                                         currentTag.numberOfLike(currentTag.numberOfLike() + 1);
                                     }
                                     currentTag.isLiked(!currentTag.isLiked());
                                 }
                             }
                         });
                 },  
                 deleteFunc: function() {
                      var answer = confirm("Do you want to delete this comment?");
                     if (answer) {
                          var currentTag = this;
                         $.ajax({
                                 url: '@Url.Action("Delete", "BookComments")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: this.id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         viewmodel.commentCollection.remove(currentTag);
                                         viewmodel.numberOfComments(viewmodel.numberOfComments() - 1);
                                     }
                                 }
                             });}
                 },

                 reportComment: function() {
                      var answer = confirm("Do you want to report this comment?");
                     if (answer) {
                         var currentComment = this;
                         $.ajax({
                                 url: '@Url.Action("ReportComment", "BookComments")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: this.id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         currentComment.isReported(true);
                                     }
                                 }
                             });}
                 }
             };
         }

         function Chapter(id, chapterName, chapterImage, numberOfPage, content, chapterNumber) {
             return {
                 Id: ko.observable(id),
                 ChapterName: ko.observable(chapterName),
                 ChapterImage: ko.observable(chapterImage),
                 NumberOfPage: ko.observable(numberOfPage),
                 Content: ko.observable(content),
                 chapterNumber: ko.observable(chapterNumber)
             };
         }

         var commentList = @CustomHelpers.BookCommentsToJavaScriptConverter(@Model.Comments.ToList()) ,
             listchapter = @CustomHelpers.ChapterToJavaScriptConverter(Model.Chapters.ToList()) ,
             contentTagList = @CustomHelpers.ContentTagsToJavaScriptConverter(@Model.ContentTags.ToList()) ,
             listUserBook = @CustomHelpers.BooksToJavaScriptConverter(userBookCollection.ToList()) ,
             listAuthorBook = @CustomHelpers.BooksToJavaScriptConverter(authorBookCollection.ToList()) ,
             viewmodel = {
                 chapterCollection: ko.observableArray(listchapter),
                 chapterTemplate: ko.observable("ListChapterTemplate"),
                 commentCollection: ko.observableArray(commentList),
                 listUserBook: ko.observableArray(listUserBook),
                 listAuthorBook: ko.observableArray(listAuthorBook),
                 comment: ko.observable(new Comment()),
                 numLike: ko.observable( @Model.NumberOfLikes ),
                 commentPageNo: ko.observable(1),
                 totalCommentPage: ko.observable( @totalCommentPage ),
                 isShowPrevBtn: ko.observable(false),
                 isShowNextBtn: ko.observable( @isShowNextButton.ToString().ToLower()),
                 numberOfComments: ko.observable( @Model.NumberOfComments ),
                 contentTagCollection: ko.observableArray(contentTagList),
                 bookId: @Model.Id ,
                 isReported: ko.observable( @Model.IsReported.BooleanToJavascript() ),
                 isLiked: ko.observable( @Model.IsLiked.BooleanToJavascript() ),
                 shareOnFacebook: function() {
                     var u = location.href;
                     var t = document.title;
                     window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436');
                     return false;
                 },
                 onRenderCommentCompleted: function(element) {
                     $(element).hover(
                         function() {
                             $(element).find('#closeButton').show();
                         },
                         function() { $(element).find('#closeButton').hide(); });
                 },
                 flag: function() {
                     var answer = confirm("Do you want to flag this book?");
                     if (answer) {
                         $.ajax({
                                 url: '@Url.Action("ReportBook", "Books")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: @Model.Id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         viewmodel.isReported(true);
                                     }
                                 }
                             });
                     }

                 },
                 like: function() {

                     if (!viewmodel.isLiked()) {
                         $.ajax({
                                 url: '@Url.Action("Like", "Books")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: @Model.Id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         viewmodel.numLike(parseInt(viewmodel.numLike()) + 1);
                                         viewmodel.isLiked(!viewmodel.isLiked());
                                     }
                                 }
                             });
                     } else {
                         $.ajax({
                                 url: '@Url.Action("UnLike", "Books")',
                                 type: 'POST',
                                 data: ko.toJSON({ id: @Model.Id }),
                                 contentType: 'APPLICATION/JSON',
                                 success: function(result) {
                                     if (result.success) {
                                         viewmodel.numLike(parseInt(viewmodel.numLike()) - 1);
                                         viewmodel.isLiked(!viewmodel.isLiked());
                                     }
                                 }
                             });
                     }
                 },
                 deleteBook: function() {
                     var answer = confirm("Do you want to delete this book?");
                     if (answer) {
                         $.ajax({
                                 url: '@Url.Action("DeleteConfirmed", "Books")',
                                 type: "POST",
                                 data: JSON.stringify({ id: @Model.Id }),
                                 dataType: "JSON",
                                 contentType: "APPLICATION/JSON; CHARSET=UTF-8",
                                 complete: function() {
                                     window.location = '@Url.Action("Index", "Account")';
                                 },
                                 error: function() {
                                     alert("error ");
                                 }
                             });
                     }
                 },
                 fetchNextCommentPage: function() {
                     $.ajax({
                             url: '@Url.Action("GetCommentByPage", "BookComments")',
                             type: 'POST',
                             data: ko.toJSON({ bookId: viewmodel.bookId, pageNumber: viewmodel.commentPageNo() + 1 }),
                             contentType: 'APPLICATION/JSON',
                             success: function(result) {
                                 if (result.isSuccess) {
                                     var listComment = [];
                                     $(result.comments).each(function(index, item) {
                                         listComment[index] = new Comment(item.id, item.username, item.userImage, item.content, item.createdDate, item.like, item.isLiked,  item.isReported,item.isAuthorized);
                                     });
                                     viewmodel.commentCollection(listComment);
                                     viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
                                     viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                                     viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                                 } else {
                                     alert(result.message);
                                 }
                             }
                         });
                 },
                 fetchPreviousCommentPage: function() {
                     $.ajax({
                             url: '@Url.Action("GetCommentByPage", "BookComments")',
                             type: 'POST',
                             data: ko.toJSON({ bookId: viewmodel.bookId, pageNumber: viewmodel.commentPageNo() - 1 }),
                             contentType: 'APPLICATION/JSON',
                             success: function(result) {
                                 if (result.isSuccess) {
                                     var listComment = [];
                                     $(result.comments).each(function(index, item) {
                                         listComment[index] = new Comment(item.id, item.username, item.userImage, item.content, item.createdDate, item.like, item.isLiked,item.isReported, item.isAuthorized);
                                     });
                                     viewmodel.commentCollection(listComment);
                                     viewmodel.commentPageNo(viewmodel.commentPageNo() - 1);
                                     viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                                     viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                                 } else {
                                     alert(result.message);
                                 }
                             }
                         });
                 },
                 postComment: function() {

                     $.ajax({
                             url: '@Url.Action("Create", "BookComments")',
                             type: 'POST',
                             data: ko.toJSON({ userId: viewmodel.userId, content: viewmodel.comment().content(), bookId: viewmodel.bookId }),
                             contentType: 'APPLICATION/JSON',
                             success: function(result) {
                                 if (result.isSuccess) {
                                     var addedComment = new Comment(
                                         parseInt(result.id),
                                         result.username,
                                         result.userImage,
                                         viewmodel.comment().content(),
                                         'few seconds ago', 0, false,false,true);
                                     viewmodel.commentCollection.unshift(addedComment);
                                     viewmodel.comment(new Comment());
                                     viewmodel.numberOfComments(viewmodel.numberOfComments() + 1);
                                 }
                             }
                         });
                 },
                 cancelPostComment: function() {
                     viewmodel.comment(new Comment());
                 }
             };

         ko.applyBindings(viewmodel);
</script>